package cn.xuqiudong.attachment.schedule;

import cn.xuqiudong.attachment.autoconfigure.AttachmentProperties;
import cn.xuqiudong.attachment.dao.BaseAttachmentOssDao;
import cn.xuqiudong.attachment.helper.AliOssHelper;
import cn.xuqiudong.attachment.model.Attachment;
import cn.xuqiudong.attachment.model.AttachmentOss;
import cn.xuqiudong.common.base.model.BaseResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;


/**
 * 说明 :  上传本地文件到ali oss de 定时器
 * @author  Vic.xu
 * @since  2022年11月16日
 */
public class OssUploadTask {

    private final Logger logger = LoggerFactory.getLogger(OssUploadTask.class);

    private final BaseAttachmentOssDao attachmentOssDao;

    private final AliOssHelper aliOssHelper;

    private final AttachmentProperties attachmentProperties;


    private final AttachmentProperties.AliOss aliOss;

    public OssUploadTask(BaseAttachmentOssDao attachmentOssDao, AliOssHelper aliOssHelper, AttachmentProperties attachmentProperties) {
        this.attachmentOssDao = attachmentOssDao;
        this.aliOssHelper = aliOssHelper;
        this.attachmentProperties = attachmentProperties;
        this.aliOss = attachmentProperties.getAliOss();
    }

    /**
     * 凌晨两点  悄悄上传到ali oss
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void upload() {
        if (!aliOss.isEnable()) {
            logger.info("未开启上传ali oss定时器清");
            return;
        }
        logger.info("ali oss  task  start......");
        long startTime = System.currentTimeMillis();
        List<Attachment> attachmentList = attachmentOssDao.findNotUploadedAttachmentList(aliOss.getOnceUploadNumber());
        if (CollectionUtils.isEmpty(attachmentList)) {
            logger.info("No files need to be uploaded to ali oss. ");
            return;
        }
        attachmentList.forEach(attachment -> {
            BaseResponse<AttachmentOss> response = aliOssHelper.upload(attachment);
            if (response.isSuccess()) {
                attachmentOssDao.saveOrUpdate(response.getData());
            } else {
                logger.info("ali oss upload attachment[{}] result:{}", attachment.getId() + attachment.getOriginalName(), response.getMsg());
            }

        });
        long endTime = System.currentTimeMillis();
        logger.info("this upload to ali oss task takes  {} ms", endTime - startTime);
    }
}

